<template>
	<view>
		<st-mc-framework :navTitle="ModuleTitle" @changeLevel="changeLevel" ref="framework"
			@AddModuleData_select='AddModuleData_select'>

			<template #content>
				<view class="content" style="width: 100%;height: 100%;">
					<view class="contentBox" style="flex: 1;">
						<view class="container">
							<u--form class="u_form" labelPosition="left" :model="baseFormData" ref="uForm">
								<u-row justify="space-between" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="设备名称:">
											<u--input v-model="baseFormData.EquipmentName" placeholder="设备名称" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="点检人:">
											<u--input v-model="baseFormData.CheckupMan" placeholder="点检人" readonly
												border="none" /></u--input>
										</u-form-item>
									</u-col>
									<u-col span="4">
										<u-form-item labelWidth="auto" label="点检日期:">
											<u--input v-model="baseFormData.BillDate" placeholder="自动带出点检日期" readonly
												border="none"></u--input>
										</u-form-item>
									</u-col>

								</u-row>
								<u-row justify="start" gutter="20">
									<u-col span="4">
										<u-form-item labelWidth="auto" label="周期:" @click="PeriodTypeShow=true">
											<u--input v-model="baseFormData.PeriodTypeName" placeholder="请选择周期" readonly
												border="none"></u--input>
											<u-icon slot="right" name="arrow-right"></u-icon>
										</u-form-item>
									</u-col>

								</u-row>
							</u--form>
						</view>
						<view class="table">
							<table>
								<tr>

									<th>序号</th>
									<th>所属分类</th>
									<th>点检内容</th>
									<th>点检方式</th>
									<th>点检标准</th>
									<th>现场照片</th>
									<th width='25%'>点检结果</th>
								</tr>
								<tr v-for="(item, index) in tableData">

									<td>{{index + 1}}</td>
									<td>
										<view class="newlineDiv"><text>{{item.EquipmentCheckTypeName}}</text></view>
									</td>
									<td>
										<view class="newlineDiv"><text>{{item.CheckupItemName}}</text></view>
									</td>
									<td>
										<view class="newlineDiv"><text>{{item.ProcessingMethod}}</text></view>
									</td>
									<td>
										<view class="newlineDiv"><text>{{item.OnStandard}}</text></view>
									</td>
									<td>
										<u-upload :fileList="item.DImgs" width="60" height="60" class="upload"
											style="display: flex;justify-content: center;align-items: center;"
											@afterRead="afterRead($event,index)" @delete="deletePic($event,index)"
											multiple :maxCount="1" :previewFullImage="true"></u-upload>
									</td>
									<td style="text-align: center;">
										<uni-data-checkbox v-model="item.FResult" :localdata="sexs" />
									</td>
								</tr>
							</table>

						</view>
					</view>

					<view class="DetailsbottomBtns">
						<button block @click="submit" class="button1">
							保 &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp &nbsp 存
						</button>
					</view>


				</view>
			</template>
		</st-mc-framework>
		<u-modal :show="modalshow" :title="modaltitle" width="400" @confirm='modalconfirm'>
			<view class="slot-content">
				{{modalcontent}}
			</view>
		</u-modal>
		<m-loading :text="loadingName" v-model="showMLoading" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>

		<u-action-sheet :actions="PeriodTypeList" :show="PeriodTypeShow" @select="PeriodTypeClick"
			@close="PeriodTypeShow=false"></u-action-sheet>
		<u-toast ref="uToast"></u-toast>
		<u-datetime-picker :show="Timeshow" v-model="value1" mode="date" @cancel='Timeshow=false'
			@close="Timeshow=false" @confirm='pickerConfirm'></u-datetime-picker>

	</view>
</template>

<script>
	import {
		getTimeStamp,
		getFormatDate,
		getFormatDateTime,
		getBefore7DateTime,
		formatDateTime,
		navigateMixin,
		baseAddModuleData_select,
		getchangeLevel
	} from '@/st_mes_zs/common/base.js';
	export default {
		mixins: [navigateMixin, baseAddModuleData_select],
		data() {
			return {


				baseFormData: {
					CheckupEquipmentID: 0,
					EquipmentName: '',
					EquipmentID: '',
					PeriodTypeName: '日',
					PeriodType: 'D',
					CheckupMan: '',
					BillDate: '',
					XTID: null,
					EquipmentTypeID: null
				},
				PeriodTypeShow: false,
				PeriodTypeList: [],
				sexs: [{
					text: '合格',
					value: 0
				}, {
					text: '不合格',
					value: 1
				}],
				tableData: [],
				routeIndex: 0,
				Timeshow: false,
				value1: Number(new Date()),
				modalshow: false,
				modaltitle: '提示',
				modalcontent: '',
				FWorkshopID: null, //模块id
				ModuleTitle: '', //标题
				showMLoading: false,
				loadingName: '正在加载中……',
			};
		},
		onReady() {
			var that = this
			uni.hideLoading();
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = that.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;
			that.FWorkshopID = MesBasicInfo.FWorkshopID;
			that.ModuleTitle = appConfigInfo.ActiveModule.ModuleName

			that.$nextTick(() => {
				setTimeout(() => {
					that.BtnShow = true;
				}, 500)
			})
			that.GetMJPeriod()
		},
		onLoad(onLoad) {
			var that = this
			that.$safeStatus({
				payload: '其他', // 要传递的数据
			});
			// 缓存状态引用
			const {
				GuyueModule,
				UserInfo,
				appConfigInfo
			} = this.$store.state;
			const {
				MesBasicInfo
			} = GuyueModule;

			// 统一处理加载状态
			const setLoading = (state) => this.showMLoading = state;
			// 主处理逻辑
			if (onLoad.CheckupEquipmentID) {
				setLoading(true);
				that.queryList(onLoad.CheckupEquipmentID)
				return;
			}
			if (onLoad.Detailsitem) {
				setLoading(true);
				const dispatchItem = JSON.parse(onLoad.Detailsitem);
				const formDefaults = {
					...dispatchItem
				}
				console.log(formDefaults);
				this.baseFormData = Object.assign(this.baseFormData, formDefaults);
			}
			// 统一处理表单默认值
			const formDefaults = {
				CheckupMan: UserInfo.EmplName,
				CheckupID: UserInfo.EmplID,
				ApplyForTime: getFormatDateTime(new Date()),
				BillDate: getFormatDateTime(new Date()),
				EquipmentID: that.baseFormData.EquipmentID ? that.baseFormData.EquipmentID : MesBasicInfo.warehouse
					.EquipmentID,
				EquipmentName: that.baseFormData.EquipmentName ? that.baseFormData.EquipmentName : MesBasicInfo
					.warehouse.EquipmentName,
			};
			this.assignFormData(this.baseFormData, formDefaults);
			setLoading(false);
			var obj = {
				value: that.baseFormData.PeriodType,
				name: that.baseFormData.PeriodTypeName
			}
			that.PeriodTypeClick(obj)
		},
		onBackPress(options) { // 监听页面返回
			if (options.from == 'navigateBack') { // 通过点击路由返回
				return false;
			} else if (options.from == 'backbutton') { // 通过外置返回
				return true;
			}
		},
		onUnload() {
			var that = this;

		},

		mounted() {
			var that = this;
		},
		methods: {
			// 创建表单赋值工具函数
			assignFormData(target, defaults = {}) {
				var that = this;
				Object.keys(defaults).forEach(key => {
					target[key] = defaults[key];
				});
				that.$forceUpdate();
			},
			replaceFormData(target, source, defaults = {}) {
				Object.keys(defaults).forEach(key => {
					target[key] = source[key] || defaults[key];
				});
				this.$forceUpdate()
			},
			async AddModuleData_select(res) {
				try {
					const backDelta = await this.GetModuleData_select(res);
				} catch (error) {
					console.error('返回操作失败:');
				}
			},
			modalconfirm() {
				var that = this
				that.modalshow = false
			},
			showModal(title, content) {
				this.modaltitle = title;
				this.modalcontent = content;
				this.modalshow = true;
			},
			GetMJPeriod() {
				var that = this
				that.Request.request('getPeriod', {
					FType: 'SBDJ'
				}, (ret) => {
					ret.data.ds.map(item => {
						item.name = item.PeriodTypeName
						item.value = item.PeriodType
					})
					that.PeriodTypeList = ret.data.ds
				})
			},
			deletePic(event, idx) {
				console.log(event);
				console.log(idx);
				this.tableData[idx].DImgs.splice(event.index, 1);
			},
			async afterRead(event, index) {
				console.log(event);
				console.log(index);
				let lists = [].concat(event.file)
				let fileListLen = this.tableData[index].DImgs.length;
				lists.map((item) => {
					this.tableData[index].DImgs.push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})

				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this.tableData[index].DImgs[fileListLen]
					this.tableData[index].DImgs.splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: this.Request.IPAgreement() + this.Request.serverIP() + result
					}))
					fileListLen++
				}
			},

			uploadFilePromise(url) {
				let that = this;
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
						url: that.Request.IPAgreement() + that.Request
							.serverIP() + '/Frame/uploadFile?dirName=' + '现场照片',
						filePath: url,
						name: 'file',
						header: {
							'Content-Type': 'multipart/form-data' // 必须设置
						},
						formData: {
							user: 'test'
						},
						success: (uploadFileRes) => {
							const data = JSON.parse(uploadFileRes.data);
							resolve(data.data)
						}
					});
				})
			},




			// 获取时间
			pickerConfirm(e) {
				var time = getFormatDateTime(e.value)
				const formDefaults = {
					BillDate: time
				};
				this.assignFormData(this.baseFormData, formDefaults);
				this.Timeshow = false
			},
			PeriodTypeClick(e) {
				var that = this
				const formDefaults = {
					PeriodType: e.value,
					PeriodTypeName: e.name
				};
				that.assignFormData(this.baseFormData, formDefaults);
				that.PeriodTypeShow = false
				that.Request.request('getCheckupItem', {
					PeriodType: e.value,
					FType: 'SBDJ'
				}, (ret) => {
					ret.data.ds.map(item => {
						item.FResult = item.FResult ? item.FResult : 0;
						item.CheckupEquipmentDeID = item.CheckupEquipmentDeID ? item
							.CheckupEquipmentDeID : 0
						item.DImgs = item.DImgs ? item.DImgs : []
					})
					that.tableData = ret.data.ds
				})
			},




			queryList(id) {
				var that = this
				try {
					that.Request.request('getCheckuEquipmentDetail', {
						CheckupEquipmentID: id
					}, (ret) => {
						that.showMLoading = false
						const [firstItem] = ret.data.ds;
						const formDefaults = {
							...firstItem,
							BillDate: firstItem.BillDate ? firstItem.BillDate.split('T')[0] : '',
							CheckupMan: firstItem.CheckupMan ? firstItem.CheckupMan : that.$store.state
								.UserInfo.EmplName,
							CheckupID: firstItem.CheckupID ? firstItem.CheckupID : that.$store.state
								.UserInfo.EmplID,
						};
						that.assignFormData(that.baseFormData, formDefaults)

						ret.data.ds1.map(item => {

							var stringArray = item.FilePath ? item.FilePath.split(',') : []
							if (stringArray[0] != '' && stringArray.length > 0) {
								item.DImgs = stringArray.map(item => ({
									url: that.Request.IPAgreement() + that.Request.serverIP() +
										item.trim()
								}));
							} else {
								item.DImgs = item.DImgs ? item.DImgs : []
							}
						})
						that.tableData = ret.data.ds1
						that.$forceUpdate()
					}, (err) => {
						that.showMLoading = false
					})
				} catch (e) {
					console.log(e)
					that.showMLoading = false
					this.$utils.hideLoading();
					this.$utils.msg('请求失败请重试')
				}
			},
			submit() {
				var that = this
				var show = true
				var msg
				if (that.tableData.length == 0) {
					msg = '请选择正确的周期'
					show = false
				}
				if (show) {

					const prefix = that.Request.IPAgreement() + that.Request.serverIP();
					var list = JSON.parse(JSON.stringify(that.tableData))
					const processedData = list.map(item => {
						if (item.DImgs.length === 0) {
							return "@";
						} else {
							return item.DImgs.map(obj => {
								if (typeof obj.url === 'string' && obj.url.startsWith(prefix)) {
									obj.url = obj.url.replace(prefix, '');
								}
								return obj.url
							}).join(',');
						}
					});
					console.log(list);
					list.forEach(item => {
						if (item.ProcessingMethod == '' || item.ProcessingMethod == null) {
							item.ProcessingMethod = '@'
						}
						if (item.OnStandard == '' || item.OnStandard == null) {
							item.OnStandard = '@'
						}

					})

					var obj = {
						CheckupMan: that.baseFormData.CheckupMan,
						EquipmentID: that.baseFormData.EquipmentID,
						CheckupEquipmentID: that.baseFormData.CheckupEquipmentID ? that.baseFormData
							.CheckupEquipmentID : 0,
						PeriodType: that.baseFormData.PeriodType,
						OnStandard: list.map(item => item.OnStandard).join(','),
						ProcessingMethod: list.map(item => item.ProcessingMethod).join(','),
						UpID: list.map(item => item.UpID).join(','),
						CheckupItemID: list.map(item => item.CheckupItemID).join(','),
						FResult: list.map(item => item.FResult).join(','),
						BillDate: that.baseFormData.BillDate,
						CheckupEquipmentDeID: list.map(item => item.CheckupEquipmentDeID).join(','),
						XTID: that.baseFormData.XTID,
						FWorkshopID: that.FWorkshopID,
						FilePath: processedData.join(',')
					}
					console.log(obj);
					that.Request.request('saveCheckupEquipment', obj, function(ret) {
						console.log(ret);
						if (ret.status == 200) {
							that.$refs.uToast.show({
								title: '保存',
								type: 'success',
								message: '保存成功'
							})
							that.queryList(ret.data.ds[0].CheckupEquipmentID)
						}
					})
				} else {
					that.showModal('提示', msg);
				}

			},
			changeLevel(list, data, row) {
				getchangeLevel(data)
				uni.$emit('refreshList');
			},
		}
	}
</script>

<style lang="scss" >
	@import "../css/index.css";

	.u-upload__button {
		margin: 0 !important;
	}

	.u-upload__wrap__preview {
		margin: 0 !important;
	}
</style>